package org.jactao.boot;

import org.jactao.common.LException;
import org.jactao.common.LServiceConfig;
import org.jactao.rpc.LAbstractServer;
import org.jactao.rpc.LContainer;
import org.jactao.common.LServerConfig;
import org.jactao.registry.LRegistryInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzetao on 2018/4/3.
 */
public class LBootstrap {

    private boolean started = false;

    private LServerConfig config;

    private LAbstractServer server;

    List<LServiceConfig> serviceConfigList = new ArrayList<>();

    public LBootstrap(LServerConfig config) {
        this.config = config;
    }

    public LBootstrap() {
    }

    public void setConfig(LServerConfig config) {
        this.config = config;
    }

    public void export(LServiceConfig serviceConfig) {
        serviceConfig.checkRequired();
        serviceConfigList.add(serviceConfig);
    }

    public synchronized void run() {

        if(config == null) {
            throw new LException("server config not found");
        }

        config.checkRequiredAndDefaulted();

        if(started) {
            return ;
        }

        started = true;

        //bean to container
        LContainer.getInstance().setServerConfig(config);

        //register service and putService
        for(LServiceConfig serviceConfig : serviceConfigList) {

            LRegistryInfo registryInfo = new LRegistryInfo();
            registryInfo.setServiceName(serviceConfig.getInterfaceClass().getName());
            registryInfo.setVersion(serviceConfig.getVersion());
            registryInfo.setAddress(config.getBindAddress());

            LContainer.getInstance().putService(
                    serviceConfig.getInterfaceClass().getName(),
                    serviceConfig.getImpl());

            config.getRegistry().register(registryInfo);
        }


        //config and start server
        server = LAbstractServer.get(config.getProtocolName());
        server.setSerializer(config.getSerializer());
        server.setBindAddress(config.getBindAddress());
        server.start();

        System.out.println("server service port on " + server.getBindAddress().getPort());
    }
}
